package com.rzico.sbl.ui.member

import android.widget.FrameLayout
import android.widget.TextView
import androidx.core.view.isVisible
import com.jeremyliao.liveeventbus.LiveEventBus
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityMemberTicketBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.CommonData
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.rzico.sbl.other.showTicketDialog
import com.rzico.sbl.other.userRole
import com.rzico.sbl.viewmodel.TicketViewModel
import com.xinnuo.common.extend.startActivityEx
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.bottomHide
import com.xinnuo.common.helper.bottomShow
import com.xinnuo.common.helper.intValue
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.utils.*
import com.xinnuo.slimadapter.SlimAdapter

class MemberTicketActivity : BaseActivity(R.layout.activity_member_ticket) {

    private val mBinding by lazy { ActivityMemberTicketBinding.bind(getRootView()) }

    private lateinit var mMemberId: String
    private lateinit var mTotalView: TextView
    private val mProductList = ArrayList<CommonData>()

    override fun getViewModel() = get<TicketViewModel>()

    override fun initData() {
        initTitle(title = "电子水票")

        initLayout()

        mBinding
            .listLayout
            .swipeRefresh
            .isRefreshing = true

        getData()
    }

    private fun initLayout() {
        when (userRole) {
            // 店主、管理员
            "1" -> {
                mMemberId.notEmpty {
                    mBinding.ticketBottom.visible()
                }
            }
        }

        mBinding
            .listLayout
            .also { layout ->
                layout.emptyLayout.also {
                    it.emptyHint.text = "暂无相关水票信息！"
                }

                layout.recycleList.apply {
                    loadLinear(
                        refresh = layout.swipeRefresh,
                        onRefresh = { getData() }
                    )

                    addItemDecoration(SpaceTBDecoration(bottom = 50f))
                    addOnScrollChanged(
                        onShow = { mBinding.ticketBottom.bottomShow() },
                        onHide = { mBinding.ticketBottom.bottomHide(52f) }
                    )

                    mAdapter = SlimAdapter.creator()
                        .register<CommonData>(R.layout.item_ticket_list) { jector, bean, index ->
                            jector.apply {
                                text(R.id.item_ticket_num, bean.stock)
                                text(R.id.item_ticket_title, bean.couponName)
                                text(
                                    R.id.item_ticket_money,
                                    "¥ ${bean.amount.formatDecimal()}"
                                )

                                with<FrameLayout>(R.id.item_ticket_bg) {
                                    it.setBackgroundResource(
                                        if (index % 2 == 1) R.mipmap.icon_member17
                                        else R.mipmap.icon_member18
                                    )
                                }
                                with<TextView>(R.id.item_ticket_money) {
                                    it.setTextColor(
                                        if (index % 2 == 1) getColorEx(R.color.colorAccent)
                                        else getColorEx(R.color.orange)
                                    )
                                }
                                clicked {
                                    startActivityEx<MemberTicketRecordActivity>(
                                        "ticketId" to bean.id
                                    )
                                }
                            }
                        }
                        .attachTo(this)
                        .addHeader(getIContext(), R.layout.header_member_ticket) { _, view ->
                            mTotalView = view.find(R.id.ticket_total)
                        }
                }
            }
    }

    override fun initListener() {
        mMemberId = intent.getExtra("memberId")

        mBinding.apply {
            ticketGive.oneClick {
                mProductList
                    .isNotEmpty()
                    .conditionElse(
                        actionTrue = ::showGiveDialog,
                        actionFalse = ::getBrandList
                    )
            }

            ticketCancel.oneClick {
                mList.none {
                    it as CommonData
                    it.stock.intValue > 0
                }.condition {
                    showToast("暂无可核销水票！")
                    return@oneClick
                }

                showCancelDialog()
            }
        }
    }

    /**
     * 核销水票
     */
    private fun cancelTicket(
        couponId: String,
        num: String,
        memo: String
    ) {
        getViewModel()
            .ticketEidt(
                BaseUrl.ticketUse,
                "couponCodeId" to couponId,
                "quantity" to num,
                "memo" to memo,
            )
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = {
                    showToast("核销水票成功！")

                    // 更新水票
                    LiveEventBus
                        .get("tickeModify")
                        .post("refresh")

                    updateList()
                }
            )
    }

    /**
     * 赠送水票
     */
    private fun addTicket(
        productId: String,
        num: String,
        memo: String
    ) {
        getViewModel()
            .ticketEidt(
                BaseUrl.ticketAdd,
                "productId" to productId,
                "memberId" to mMemberId,
                "quantity" to num,
                "memo" to memo,
            )
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = {
                    showToast("赠送水票成功！")

                    // 更新水票
                    LiveEventBus
                        .get("tickeModify")
                        .post("refresh")

                    updateList()
                }
            )
    }

    /**
     * 水票品牌列表
     */
    private fun getBrandList() {
        getViewModel()
            .ticketPdt()
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = {
                    mProductList.addItems(it)
                    showGiveDialog()
                }
            )
    }

    /**
     * 水票列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .ticketList(intent.getExtra("cardId"))
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = {
                    mList.apply {
                        clear()
                        addItems(it)
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    val ticketCount = mList.sumOf {
                        it as CommonData
                        it.stock.intValue
                    }
                    mTotalView.text = "剩余总计：${ticketCount} 张"

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 更新列表
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getData()
    }

    /**
     * 显示赠送弹框
     */
    private fun showGiveDialog() {
        showListDialog(
            title = "请选择水票",
            items = mProductList.map { it.name.orEmpty() },
            listener = { index, hint ->
                mPosition = index

                showTicketDialog(
                    name = hint,
                    title = "赠送水票",
                    isForced = true,
                    onDismiss = { mPosition = -1 },
                    onSure = { num, memo ->
                        addTicket(mProductList[mPosition].productId, num, memo)
                    },
                    onSelect = { tvHint, _ ->
                        showListDialog(
                            title = "请选择水票",
                            items = mProductList.map { it.name.orEmpty() },
                            index = mPosition,
                            listener = { index, hint ->
                                mPosition = index
                                tvHint.text = hint
                            }
                        )
                    }
                )
            }
        )
    }

    /**
     * 显示核销弹框
     */
    private fun showCancelDialog() {
        val itemList =
            mList.filter { (it as CommonData).stock.intValue > 0 }

        showListDialog(
            title = "请选择水票",
            items = itemList.map { (it as CommonData).couponName },
            listener = { index, _ ->
                mPosition = index
                val item = itemList[mPosition] as CommonData

                showTicketDialog(
                    name = item.couponName,
                    title = "核销水票",
                    maxCount = item.stock.intValue,
                    isForced = true,
                    onSure = { num, memo ->
                        cancelTicket((itemList[mPosition] as CommonData).id, num, memo)
                    },
                    onSelect = { tvHint, max ->
                        showListDialog(
                            title = "请选择水票",
                            items = itemList.map { (it as CommonData).couponName },
                            index = mPosition,
                            listener = { index, hint ->
                                mPosition = index

                                tvHint.text = hint
                                max[0] = (itemList[mPosition] as CommonData).stock.intValue
                            }
                        )
                    }
                )
            }
        )
    }

}